<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use app\index\model\Personals;
use app\index\model\Users;
class registe extends Common
{
    /*注册*/
    public function add()
    {    $data=input('post.');
      file_put_contents('001.txt',json_encode($data));  
        $gender = Request::instance()->post('gender','3');
        //echo $gender;die;
        if($gender==3){
            return json(['state'=>'202','msg'=>'性别为空']);
        }
        $birthday=Request::instance()->post('birthday','');//年龄
        $constellation=Request::instance()->post('constellation','');//
        if(empty($birthday) || empty($constellation)){
          return json(['state'=>'203','msg'=>'年龄为空']);
        }
        $uriqi=strtotime($birthday);  
        $age=$this->getAge($uriqi);//计算年龄
        $university=input('university','');//大学
        if(empty($university)){
          return json(['state'=>'204','msg'=>'学校为空']);
        }
        $province=input('province','');//省份
        if(empty($province)){
           return json(['state'=>'205','msg'=>'省份为空']);
        }
        $city=input('city','');//市级
        if(empty($city)){
             return json(['state'=>'206','msg'=>'城市为空']);
        }
        $uid=input('uid','');//获取用户的uid
        file_put_contents('filename.txt',$uid);
        $openId=input('openId','');//获取opneId
         file_put_contents('filename00011.txt',$openId);
        $height=input('height','');//身高
        file_put_contents('filename001.txt',$height);
        $marriage=(int)input('marriage','3');//婚姻状况
        if($marriage==3){
          return json(['state'=>'206','msg'=>'婚姻状况为空']);
        }
        $userPhone=input('userPhone','');//手机号
        $loginPwd=input('loginPwd');//登录密码
         file_put_contents('filename0002.txt',$loginPwd);
        $nickname=input('nickname');//用户昵称
        file_put_contents('filename0001.txt',$nickname);
        // $sef_desc=input('sef_desc');//个人资料
        $type_id=input('type_id');//学历  1专科 2本科 3硕士 4博士 
        file_put_contents('file000001.txt',$type_id);
        if(!empty($height)  && !empty($nickname) && !empty($uid) && !empty($openId) && !empty($loginPwd) && !empty($type_id)){
            //登录密码加密
            $loginword=md5($loginPwd);
            //检测手机号是否存在
           $rs=Db::name('user_info')
                 ->where(['openId'=>$openId])
                 ->field('userPhone,openId') 
                 ->find();
           if(!empty($rs['userPhone'])){
              return json(['state'=>'207','msg'=>'你已经注册过啦']); 
           }else{
              $data=['gender'=>$gender,'birthday'=>$birthday,'age'=>$age,'university'=>$university,'province'=>$province,'city'=>$city,'height'=>$height,'type_id'=>$type_id,'constellation'=>$constellation,'marriage'=>$marriage,'userPhone'=>$userPhone,'nickname'=>$nickname,'loginPwd'=>$loginword];
                $rd=Personals::Myadd($openId,$data);
                 if($rd){
                        $result= Users::phoneSel($userPhone);
                            $nonce='abcb123';
                            $ctime=time();
                            $csum=sha1('572faf2b1b76'.$nonce.$ctime);
                            $headers = array();
                            $headers[] = 'AppKey: 98b90dd621eef6bfc37b9a2917a96776';
                            $headers[] = 'Nonce: '.$nonce;
                            $headers[] = 'application/x-www-form-urlencoded;charset=utf-8;';
                            $headers[] = 'CurTime: '.$ctime;
                            $headers[] = 'CheckSum: '.$csum;
                            $post_data=['accid'=> $result['uid'],'name'=>$result['nickname']];
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            curl_setopt($ch, CURLOPT_URL,'http://api.netease.im/nimserver/user/create.action');
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                            $output = curl_exec($ch);
                            curl_close($ch);
                            $obj=json_decode($output);
                            //print_r($output);die;
                            $arr=$this->object2array($obj);
                            $code=$this->object2array($arr['code']);
                            //print_r($code);die;
                            if($code==200){
                              $Info=$this->object2array($arr['info']);
                            }else{
                              $output=$this->token($result['uid'],$result['nickname']);
                              $obj=json_decode($output);
                              $arr=$this->object2array($obj);
                              $codeSet=$this->object2array($arr['code']);
                              if($codeSet==200){
                                  $Info=$this->object2array($arr['info']); 
                              }else{
                                return json(['state'=>'213','msg'=>'网易云注册失败']);
                              }
                            }
                            $token=$Info['token'];
                            $arr1['token']=$token;
                            $arr1['accid']=$Info['accid'];
                            $token=$Info['token'];
                            $arr1['token']=$token;
                            $result=['token'=>$token,'accid'=>$Info['accid'],'uid'=>$result['uid'],'nickname'=>$result['nickname']];
                            $rk=Db::name('user_info')->where(['userPhone'=>$userPhone])->update($arr1);
                            if($rk){
                  return json($this->array_nonull(['state'=>'200','msg'=>'注册成功等在审核','result'=>$result])); 
                            }else{
                              return json(['state'=>'201','msg'=>'注册失败']); 
                            }
                      }else{
                        return json(['state'=>'201','msg'=>'未获取微信信息']); 
                    }
           }
        }else{
           return json(['state'=>'209','msg'=>'参数缺失']);
        }
        
    }
     //更新并获取新token
    public function token($uid,$nickname){
        $rd=Db::name('user_info')->where("uid=$uid")->find();
        if($rd){
            $nonce='abcb123';
            $ctime=time();
            $csum=sha1('572faf2b1b76'.$nonce.$ctime);
            $headers = array();
            $headers[] = 'AppKey: 98b90dd621eef6bfc37b9a2917a96776';
            $headers[] = 'Nonce: '.$nonce;
            $headers[] = 'application/x-www-form-urlencoded;charset=utf-8;';
            $headers[] = 'CurTime: '.$ctime;
            $headers[] = 'CheckSum: '.$csum;
            $data=['accid'=>$uid,'name'=>$nickname];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_URL,'http://api.netease.im/nimserver/user/refreshToken.action');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $output = curl_exec($ch);
            curl_close($ch);
            $obj=json_decode($output);
            $arr=$this->object2array($obj);
            $code=$this->object2array($arr['code']);
            if($code==200){
              return $output;
            }else{
              exit(json(['state'=>'201','msg'=>'获取失败','result'=>json_decode($output)]));
            }
        }else{
          $return=['state'=>'201','msg'=>'请求参数有误!'];
        }  
       return json($return);
}

/*
     * @获取验证码
     * @函数 get_register_verify
     * @功能 获取账号注册的验证码
     * @参数 [mobile:手机号]
     */
    public function get_register_verify()
    {
        $userPhone = input('userPhone');//手机号
        if(empty($userPhone)){
            return json(['state'=>'204','msg'=>"数据缺失,手机号不能为空"]);
        }
       if(mb_strlen($userPhone)!='11'){
            return json(['state'=>'205','msg'=>'手机号格式不正确']);
        }else{
       $code = mt_rand(111111,999999);//设置随机数
        $re=Db::name('user_info')->where(['userPhone'=>$userPhone])->find();
        if($re){
           return json(['state'=>'206','msg'=>'您注册的手机号已存在']); 
        }else{
          $rs=Db::name('mobile')->where("userPhone=$userPhone")->find();
          if($rs){
            $data=['time'=>date("Y-m-d H:i:s"),'num'=>$code];
            $res=Db('mobile')->where("userPhone=$userPhone")->update($data);
            if($res){
               $rd=Db::name('mobile')->where("userPhone=$userPhone")->find();
               $num1=$rd['num'];
            }else{
                return json(['state'=>'203','msg'=>'存储验证码失败']); 
            }
         }else{
            $sdata=['time'=>date("Y-m-d H:i:s"),'num'=>$code,'userPhone'=>$userPhone]; 
           $rk=Db::name('mobile')->insert($sdata);
           if(empty($rk)){
             return json(['state'=>'203','msg'=>'存储验证码失败']); 
           }else{
             $re3=Db('mobile')->where("userPhone=$userPhone")->find();
              $num1=$re3['num'];
           }
         } 
        } 

        header('content-type:text/html;charset=utf-8');
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
      
        $smsConf = array(
        'key'   => '14ed239162b132b8009fe878b529951a', //您申请的APPKEY
        'mobile'    => "$userPhone", //接受短信的用户手机号码
        'tpl_id'    => '78391', //您申请的短信模板ID，根据实际情况修改
        'tpl_value' =>'#code#='.$num1 //您设置的模板变量，根据实际情况修改
        );
       // Cache::set($mobile.'_code',$code,3600);
        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信
       // print_r($content);die;
        if($content){
        $result = json_decode($content,true);
        $error_code = $result['error_code'];
        if($error_code == 0){
        //状态为0，说明短信发送成功
        // echo "短信发送成功,短信ID：".$result['result']['sid'];
            return json(['state'=>200,'mesg'=>"短信发送成功"]);
        }else{
        //状态非0，说明失败
        $msg = $result['reason'];
        // echo "短信发送失败(".$error_code.")：".$msg;
        return json(['state'=>201,'msg'=>"短信发送失败(".$error_code."):".$msg]);
        }
        }else{
        //返回内容异常，以下可根据业务逻辑自行修改
        // echo "请求发送短信失败";
        return json(['state'=>202,'msg'=>"请求发送短信失败"]);
        }   
    }
  }
  //默认获取微信用户
  public function aquire(){
    $openId = input('openId');//微信opneid
        if(empty($openId)){
            return json(['state'=>'203','msg'=>"参数为空"]);
        }
      $data=['openId'=>$openId];//获取opneId  
      //判断该微信用户是否入库
      $re=Db::name('user_info')->where(['openId'=>$openId])->find();
      if($re){
        $result=['uid'=>$re['uid'],'openId'=>$re['openId']];
         return json(['state'=>'200','msg'=>'添加成功','result'=>$result]);
      }
     $user_info=Db::name('user_info')->insertGetId($data);
     if($result){
       $result=['uid'=>$user_info,'openId'=>$openId];
       return json(['state'=>'200','msg'=>'添加成功','result'=>$result]);
     }else{
      return json(['state'=>'201','msg'=>'添加失败再试试']);
     }
  }
        
}


